import { defineStore } from 'pinia'
import type { IDialog, IHandleApi } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IAsset, IAssetRecord } from '@/types/asset'
import {
  addAssetApi,
  deleteAssetApi,
  queryAssetApi,
  queryAssetCategoryApi,
  updateAssetApi
} from '@/apis/asset'

export const useAssetStore = defineStore('asset', {
  state: () => ({
    assetRecordList: [] as IAssetRecord[],
    assetList: [] as IAsset[],
    totalAsset: 0,
    queryInfo: {
      category: ''
    },
    assetApiType: 'ADD' as IHandleApi,
    categoryList: [] as string[],
    currentAssetRecord: {
      id: 0,
      category: '',
      name: '',
      remark: '',
      owner: '',
      amount: 0
    } as IAssetRecord,
    assetDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IAssetRecord>,
    isRefresh: false
  }),
  actions: {
    async queryAssetList() {
      this.assetRecordList = await queryAssetApi(this.queryInfo.category || '')

      this.assetList = []
      this.parseAssetList()
    },
    parseAssetList() {
      const groupedData = this.assetRecordList.reduce((acc, item) => {
        const { category } = item
        if (!acc[category]) {
          acc[category] = []
        }
        acc[category].push(item)
        return acc
      }, {})

      this.assetList = Object.entries(groupedData).map(([category, group]) => {
        const totalAmount = group.reduce((sum, { amount }) => sum + amount, 0)
        const itemList = group.map(({ id, name, remark, owner, amount }) => ({
          id,
          name,
          remark,
          owner,
          amount
        }))
        return {
          category,
          totalAmount,
          itemList
        }
      })

      this.totalAsset = this.assetList.reduce((sum, current) => sum + current.totalAmount, 0)
    },
    async queryAssetCategory() {
      this.categoryList = await queryAssetCategoryApi()
    },
    async handleAssetApi(asset: IAssetRecord) {
      switch (this.assetApiType) {
        case 'ADD':
          await addAssetApi(asset)
          ElMessage.success('新增资产成功')
          break
        case 'UPDATE':
          await updateAssetApi(asset.id as number, asset)
          ElMessage.success('更新资产成功')
          break
        case 'DELETE':
          await deleteAssetApi(asset.id as number)
          ElMessage.success('删除资产成功')
          break
        default:
          break
      }
      this.assetDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryAssetList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyAsset(): IAssetRecord {
      return {
        amount: 0,
        category: '资金账户',
        name: '',
        owner: '',
        remark: ''
      }
    }
  }
})
